/*
 * Copyright 2006-2008 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package org.apache.servicemix.examples.restful.springdm;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;

import org.springframework.osgi.samples.weather.service.WeatherService;

/**
 *
 * @author Roberto Rojas
 *
 *
 */

@Path("/service/")
@Produces("application/xml")
public class WeatherServiceFrontEnd {

	private static final String DEFAULT_DATE_FORMAT = "MM-dd-yyyy";

	private WeatherService weatherService;

	public WeatherServiceFrontEnd() {
		System.out.println("Instantiating " + getClass().getCanonicalName());
	}

	public WeatherService getWeatherService() {
		return weatherService;
	}

	public void setWeatherService(WeatherService weatherService) {
		System.out.println(getClass() + " setting weatherService: " + weatherService);
		this.weatherService = weatherService;
	}

	@GET
    @Produces({"application/xml","application/json"})
    @Path("/historical-high/{date}")
	public String getHistoricalHighForDate(@PathParam("date") String dateStr) {
      	StringBuffer xml = new StringBuffer("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
    	xml.append("<historical-high>");
    	xml.append("<year>");
    	Date date = convertStringToDate(dateStr);
    	xml.append(date.toString());
    	xml.append("</year>");
    	xml.append("<temperature>");
    	xml.append(weatherService.getHistoricalHigh(date));
    	xml.append("</temperature>");
    	xml.append("</historical-high>");
		return xml.toString();
    }

	private Date convertStringToDate(String dateStr) {
		Date convertedDate = null;
		try {
			String dateFormat = DEFAULT_DATE_FORMAT;
			convertedDate = new SimpleDateFormat(dateFormat).parse(dateStr);
		} catch (ParseException e) {
			e.printStackTrace();
			convertedDate = new Date();
		}
		return convertedDate;
	}


    final void init() {
        System.out.println("init called");
    }


}
